package engine.web;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.CronExpression;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import engine.dataobjects.MailItemInstance;
import engine.services.IContentService;
import engine.services.IDataResource;
import engine.services.IMailService;
import engine.utils.DateUtils;

@Controller
@RequestMapping("/cron")
public class CronController {
	@Autowired
	IContentService contentService;
	@Autowired
	IDataResource configResource;
	@Autowired 
	IMailService mailService;
	@Autowired
	DateUtils dateUtil;

	String defaultCronExpression;

	
	private static Log log = LogFactory.getLog(CronController.class);
       
    public void setDateUtil(DateUtils dateUtil) {
		this.dateUtil = dateUtil;
	}

	public void setDefaultCronExpression(String defaultCronExpression) {
		this.defaultCronExpression = defaultCronExpression;
	}


	public void setMailService(IMailService mailService) {
		this.mailService = mailService;
	}

	public void setConfigResource(IDataResource configResource) {
		this.configResource = configResource;
	}

	public void setContentService(IContentService contentService) {
		this.contentService = contentService;
	}
	
	
	@RequestMapping(value="/mail", method=RequestMethod.GET)
	public @ResponseBody String mailItems() throws IOException {
		log.info("Running Cron on mailitems");
		try {
			this.configResource.init();
			this.configResource.refresh();		
			log.info("Refreshed Configuration");
			Date lastCronTime = org.apache.commons.lang.time.DateUtils.addHours(dateUtil.getNow(), (-1 * dateUtil.getNumberOfHoursForTrigger()));
			log.info("Last Cron Time: " + lastCronTime.toString());
			List<MailItemInstance<?>> activeItems = this.configResource.getActiveMailItemInstances();
			for (MailItemInstance<?> instance : activeItems) {
				log.info("Checking: " + instance.getItem().getName());
				String jobInterval = instance.getJobInterval();
				if (jobInterval == null) {
					jobInterval = defaultCronExpression;
				}
				CronExpression ce = new CronExpression(jobInterval);
				Date nextRun = ce.getNextValidTimeAfter(lastCronTime);
				log.info("Next Run: " + nextRun.toString());
				if (nextRun.getTime() <= System.currentTimeMillis()) {
					log.info("Mailing " + instance.getItem().getName() + " which should have been sent at " + nextRun);
					mailService.mail(instance);
				}
				
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return "Cron job ran succesfully";
	}
}
